package com.st.security.config;

import com.alibaba.fastjson.JSON;
import com.st.security.base.result.STResult;
import com.st.security.jwt.JwtTokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @创建人: 放生
 * @创建时间: 2022/4/6
 * @描述: 认证成功的处理器
 */
@Component("customAuthenticationSuccessHandler")
public class CustomAuthenticationSuccessHandler implements AuthenticationSuccessHandler {


    @Autowired
    private RedisTemplate redisTemplate;

    @Resource
    JwtTokenUtil jwtTokenUtil;

    /**
     * 认证成功后处理逻辑
     * @param authentication 封装了用户信息 UserDetails，访问IP等
     */
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request,
                                        HttpServletResponse response,
                                        Authentication authentication) throws IOException, ServletException {
       //登入成功以后把用户的权限信息让存入redis中，可以 为 token value为用户的信息
        UserDetails userDetails = (UserDetails) authentication.getPrincipal();
        System.out.println(userDetails);
        String token = jwtTokenUtil.generateToken(userDetails);
        redisTemplate.opsForValue().set(token, JSON.toJSONString(userDetails));

        // 当认证成功后，响应 JSON 数据给前端
        STResult result = STResult.ok(token);
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().write(result.toJsonString());

    }

}
